package org.correct.crawler;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

import org.correct.model.HtmlItem;
import org.correct.util.Queue;

public class StoreManager {
	private class StoreHandler extends Thread {
		public void run() {
			HtmlItem text = null;
			try {
				while(true) {
					while((text = textQueue.poll()) == null) {
						synchronized(StoreManager.this) {
								StoreManager.this.wait();
						}
					}
					
					// write the file to the specified output directory
				
					writeFile(text);
				}
			} catch (InterruptedException e) {
				// e.printStackTrace();
				System.out.println(this.getName() + " shutdown ...");
			}
		}
	}
	
	private Queue<HtmlItem> textQueue;
	private final int maxThreadNum;
	private StoreHandler[] handler;
	private String fileBase;
	
	public StoreManager(String fileBase) {
		maxThreadNum = 50;
		textQueue = new Queue<HtmlItem>();
		handler = new StoreHandler[maxThreadNum];
		this.fileBase = fileBase;
	}
	
	public StoreManager(String fileBase, int maxThreadNum) {
		this.maxThreadNum = maxThreadNum;
		textQueue = new Queue<HtmlItem>();
		handler = new StoreHandler[this.maxThreadNum];
		this.fileBase = fileBase;
	}
	
	public void start() {
		for(int i = 0; i < handler.length; i++) {
			handler[i] = new StoreHandler();
			handler[i].start();
		}
	}
	
	public void shutDown() {
		for(int i = 0; i < handler.length; i++) {
			while(handler[i].getState() != Thread.State.WAITING);
			handler[i].interrupt();
		}
	}
	
	/*
	public void addFile(String text) {
		textQueue.add(new HtmlItem(text, "gbk"));
		synchronized(this) {
			notify();
		}
	}*/
	
	public void addFile(int id, String text, String encoding) {
		textQueue.add(new HtmlItem(id, text, encoding));
		synchronized(this) {
			notify();
		}
	}
	
	public void addFile(HtmlItem html) {
		System.out.println("-> " + Thread.currentThread() + " in addFile()");
		textQueue.add(html);
		synchronized(this) {
			notify();
		}
	}
	
	private void writeFile(HtmlItem htmlItem) {
		System.out.println(
				"w> " + Thread.currentThread() + " Writing file #" + htmlItem.id);
		String fileName = fileBase + "/" + htmlItem.id + ".html";
		try {
			PrintWriter w = new PrintWriter(fileName, htmlItem.encoding);
			w.println(htmlItem.html);
			w.flush();
			w.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (Exception e) {
			File f = new File(fileName);
			f.delete();
		}
	}
	
	public int queueLength() {
		return textQueue.size();
	}
}
